#/usr/bin/bash
java -version

if [ $? -ne 0  ];then
	echo "--------------请先安装jdk,退出脚本------------"
	exit
fi


INSTALL_PATH=$1
if [ ! $INSTALL_PATH ];then
	INSTALL_PATH="/usr/local/tomcat"
fi

#Tomcat架包下载路径,不传默认ftp://ftpUser:123456@175.178.190.189/tomcat/tomcat-8.5.79/apache-tomcat-8.5.79.tar.gz
DOWNLOAD_URL=$2
if [ ! $DOWNLOAD_URL ];then
	DOWNLOAD_URL="ftp://ftpUser:123456@175.178.190.189/tomcat/tomcat-8.5.79/apache-tomcat-8.5.79.tar.gz"
fi


#如果文件夹不存在，创建文件夹
if [ ! -d $INSTALL_PATH ];then
   mkdir $INSTALL_PATH
fi

cd $INSTALL_PATH

#wget下载文件
wget $DOWNLOAD_URL

##获取文件名
FILENAME=${DOWNLOAD_URL##*/};

#判断当前文件是什么压缩包
if [ ${FILENAME##*.} = gz ];then
  TEMP=${FILENAME%.*}
    if [ ${TEMP##*.} = tar ];then
        tar -zxvf $FILENAME -C $INSTALL_PATH
    else
        unzip  $FILENAME -d  $INSTALL_PATH
    fi
elif [ ${FILENAME##*.} = zip ];then
    unzip  $FILENAME -d  $INSTALL_PATH
fi

#获取解压后当前目录下的文件名
NEW_FILENAME=`ls -lt $INSTALLPATH |grep tomcat|head -n 1|awk '{print $9}'`;

if [ ! $NEW_FILENAME ];then
  echo "解压失败，获取不到解压后的文件名，退出脚本";
  exit
fi

#删除安装包
rm -rf $INSTALL_PATH/$FILENAME

#配置Tomcat环境变量
cd /etc/profile.d

#创建tomcat_env.sh文件并配置环境变量
#先判断文件是否已经存在，若存在先删除
if [ -f tomcat_env.sh ];then
	rm -rf tomcat_env.sh;
fi

#配置Tomcat环境变量
cat >>/etc/profile.d/tomcat_env.sh<<EOF 
export CATALINA_HOME=$INSTALL_PATH/$NEW_FILENAME
export PATH=\$PATH:\$CATALINA_HOME/bin
EOF

#重启/ect/profile环境
source /etc/profile


#tomcat配置服务
cd /etc/init.d

if [ -f tomcat ];then
        rm -rf tomcat;
fi

#配置Tomcat配置服务
cat >>/etc/init.d/tomcat<<EOF 
#!/bin/bash
 
# dcription: Tomcat8 Start Stop Restart
 
# processname: tomcat8
 
# chkconfig: 234 20 80
 
CATALINA_HOME=$INSTALL_PATH/$NEW_FILENAME
case \$1 in
 
start)
 
echo "Starting Tomcat..."
 
sh $CATALINA_HOME/bin/startup.sh
 
;;
 
stop)
 
echo "Stopping Tomcat..."
 
sh $CATALINA_HOME/bin/shutdown.sh
 
;;
 
restart)
 
echo "Stopping Tomcat..."
 
sh $CATALINA_HOME/bin/shutdown.sh
 
sleep 2
 
echo
 
echo "Starting Tomcat..."
 
sh $CATALINA_HOME/bin/startup.sh
 
;;
 
*)
 
echo 'please use : tomcat {start | stop | restart}'
 
;;
 
esac
 
exit 0
EOF

chmod 777 /etc/init.d/tomcat

cd $INSTALL_PATH/$NEW_FILENAME/bin

cp setclasspath.sh setclasspath_backups.sh

if [ ! $JAVA_HOME ];then
	echo "找不到JAVA_HOME环境变量值，请检查java是否安装，并且\$JAVA_HOME命令能够获取环境变量值，即将退出脚本"
	exit
fi

sed -i "/^.*\/bin\/sh.*$/a  export JAVA_HOME=$JAVA_HOME" setclasspath.sh
sed -i "/^.*\/bin\/sh.*$/a  export JRE_HOME=\$JRE_HOME" setclasspath.sh

chkconfig --add tomcat

chkconfig tomcat on

echo $JAVA_HOME

#tomcat启动
service tomcat start

if [ $? -ne 0 ];then
        echo "-----------------------tomcat安装失败，请排查!!!，退出脚本----------------------";
        exit;
else
	echo "-----------------------tomcat安装成功，请稍后手动登录云服务器,在安全组中放通8080端口----------------------";
fi
